package org.androbuzz;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.util.Log;

public class AndroBuzzAPIHandler {
	private AndroBuzzSAXHandler mSaxHandler = new AndroBuzzSAXHandler();
	
    private AndroBuzzDbAdapter mDbHelper;
    private final String mURLGoogleAPI = "https://www.googleapis.com/buzz/v1/activities/";
    private final int mMaxResult = 200;
    private Context mContext;
    
    public AndroBuzzAPIHandler(Context ctx)
    {
    	mContext = ctx;
    	mDbHelper = new AndroBuzzDbAdapter(ctx);
	    
		mDbHelper.open();
    }
    
    public void finalize()
    {
    	mDbHelper.close();  
    }
    
    public int retrieveBuzzAndComments(String google_name)
    {
    	int nbBuzzCreated = 0;
    	int nbCommentsCreated = 0;
    	
    	List<String> commentList = new ArrayList<String>();
    	
		try {
			AndroBuzzSAXHandler.Feed curFeed = null;
			URL feedUrl = new URL(mURLGoogleAPI + google_name + "/@public?alt=atom&max-results="+mMaxResult);
			boolean continueGetFeed;
			do {
				continueGetFeed = false;
				curFeed = mSaxHandler.createBuzzReader(mContext, feedUrl);
				
				if(checkFeedIntegrity(curFeed))
				{
					Log.i("AndroBuzz API Handler info", "have " + curFeed.mActivityList.size() + " buzz in feed");
					if(curFeed.mActivityList.size() > 0 && curFeed.mActivityList.get(0).author != null)
					{
						String update_activity_time = curFeed.mActivityList.get(0).date_updated;
						if(update_activity_time == null)
							update_activity_time = curFeed.mActivityList.get(0).date_published;
						
						Long author_id = mDbHelper.getAuthorCreateOrUpdateIfn(curFeed.author_google_id_key, curFeed.author_google_id_name, curFeed.mActivityList.get(0).author, curFeed.mActivityList.get(0).author_photo_url, update_activity_time);
						for(AndroBuzzSAXHandler.Activity lBuzz: curFeed.mActivityList)
						{
							if(checkBuzzIntegrity(lBuzz))
							{
								//TODO: check for update, add and delete (create list of ids)
								if(mDbHelper.findBuzzByGoogleBuzzId(lBuzz.activityId) == -1)
								{
									mDbHelper.createOrUpdateBuzz(curFeed.feedId, author_id.toString(), lBuzz);
									nbBuzzCreated++;
								}
								
								if(!lBuzz.nb_comments.equals("0"))
								{
									commentList.add(lBuzz.activityId);
								}
							}									
							else
								Log.w("AndroBuzz API Handler info", "buzz not valid !   lBuzz.buzzId: " + lBuzz.activityId + " lBuzz.author: " + lBuzz.author + " author_key " + lBuzz.author_key + " date_published: " +  lBuzz.date_published + " date_updated: " + lBuzz.date_updated + " summary: " + lBuzz.summary + " content: " + lBuzz.content);
						}
						if(curFeed.nextLink != null)
						{
							Log.i("AndroBuzz API Handler info", "have next buzz href: " +  curFeed.nextLink);
							continueGetFeed = true;
							feedUrl = new URL(curFeed.nextLink);
						}
					}
				}
				else
					Log.w("AndroBuzz API Handler info", "Feed integrity check failed");
			}
			while(continueGetFeed);	
			
			for(String lBuzz: commentList)
			{
				nbCommentsCreated += retrieveCommentForBuzz(lBuzz, google_name);
			}

		} catch (MalformedURLException e) {
			Log.e("AndroBuzz Malformed URL Exception", e.toString());
			e.printStackTrace();
		}
		
    	return nbBuzzCreated;
    }
    
    private boolean checkFeedIntegrity(AndroBuzzSAXHandler.Feed feedToTest)
    {
    	return feedToTest != null && feedToTest.author_google_id_key != null && 
    	feedToTest.author_google_id_key.length() > 0 && feedToTest.kind != null && 
    	feedToTest.kind.equals("buzz#activityFeed");
    }
    
    private boolean checkBuzzIntegrity(AndroBuzzSAXHandler.Activity buzzToTest)
    {
    	return (buzzToTest.author_photo_url != null && buzzToTest.activityId != null && buzzToTest.author != null && buzzToTest.date_published != null && buzzToTest.summary != null && buzzToTest.content != null && buzzToTest.nb_comments != null);
    }
    
    private boolean checkCommentFeedIntegrity(AndroBuzzSAXHandler.Feed feedToTest)
    {
    	return feedToTest.kind != null && 
    	feedToTest.kind.equals("buzz#commentFeed");
    }
    
    private boolean checkCommentIntegrity(AndroBuzzSAXHandler.Activity buzzToTest)
    {
    	return (buzzToTest.author_photo_url != null && buzzToTest.author != null && buzzToTest.author_key != null && buzzToTest.activityId != null && buzzToTest.content != null && buzzToTest.date_published != null);
    }
    
    public int retrieveCommentForBuzz(String buzzId, String authorId)
    {
    	int nbCommentsCreated = 0;
    	
		try {
			URL feedUrl = new URL("https://www.googleapis.com/buzz/v1/activities/" + authorId + "/@self/" + buzzId + "/@comments?alt=atom&max-results="+mMaxResult);
			Log.w("AndroBuzz SAX info", "get comments for buzz: " + buzzId);
			AndroBuzzSAXHandler.Feed curFeed = null;
			curFeed = mSaxHandler.createBuzzReader(mContext, feedUrl);
			
			if(checkCommentFeedIntegrity(curFeed))
			{
				for(AndroBuzzSAXHandler.Activity lBuzz: curFeed.mActivityList)
				{
					if(checkCommentIntegrity(lBuzz))
					{
						Long author_id;
						String update_activity_time = lBuzz.date_updated;
						if(update_activity_time == null)
							update_activity_time = lBuzz.date_published;
						
						if(AndroBuzzSAXHandler.checkAuthorIdIsKey(lBuzz.author_key))
							author_id = mDbHelper.getAuthorCreateOrUpdateIfn(lBuzz.author_key, null, lBuzz.author, lBuzz.author_photo_url, update_activity_time);
						else
							author_id = mDbHelper.getAuthorCreateOrUpdateIfn(null, lBuzz.author_key, lBuzz.author, lBuzz.author_photo_url, update_activity_time);
						
						Long rowBuzzId = mDbHelper.findBuzzByGoogleBuzzId(buzzId);
						
						if(rowBuzzId != -1)
						{
							if(mDbHelper.findCommentById(lBuzz.activityId) == -1)
							{
								Log.w("AndroBuzz SAX info", "Comment lBuzz.buzzId: " + lBuzz.activityId + " author: " + lBuzz.author + " author_key " + lBuzz.author_key + " date_published: " +  lBuzz.date_published + " date_updated: " + lBuzz.date_updated + " summary: " + lBuzz.summary + " content: " + lBuzz.content);
								mDbHelper.addComment(lBuzz.activityId, String.valueOf(author_id), lBuzz.date_published, lBuzz.content, false, rowBuzzId);
								nbCommentsCreated++;
							}
						}
						else
							Log.w("AndroBuzz SAX info", "Buzz not found !");
					}
					else
						Log.w("AndroBuzz SAX info", "Comment is not complete !");
				}
			}
			else
				Log.w("AndroBuzz SAX info", "Feed Comment invalid !");
			
		} catch (MalformedURLException e) {
			Log.e("AndroBuzz Malformed URL Exception", e.toString());
			e.printStackTrace();
		}
	
		return nbCommentsCreated;
    }
	
}
